using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using SuCasa.Infrastructure;
using SuCasa.Models;

namespace SuCasa.DataAccess{
    public interface ICourseRepository {
        bool AddCourse(Course course);
        List<Course> GetAll();
        Course GetCourseBy(Func<Course, bool> func);
        CourseDisplayViewModel GetCourseSessions(Course course);
        void RemoveStudentFromCourse(int courseId, int id);
    }

    public class CourseRepository : ICourseRepository{
        readonly SuCasaDbContext _context;
        readonly SessionRepository _sessionRepository;
        readonly MemberRepository _memberRepository;

        public CourseRepository(SuCasaDbContext context)
        {
            _context = context;
            _sessionRepository = new SessionRepository(context);
            _memberRepository = new MemberRepository(context);
        }

        public bool AddCourse(Course course){
            if (course.CourseId == 0)
            {
                _context.Courses.Add(course);
            }
            else
            {
                _context.Courses.Attach(course);
                _context.Entry(course).State = EntityState.Modified;

            }
            return _context.SaveChanges() > 0;
        }

        public List<Course> GetAll()
        {
          return _context.Courses.Include("Students").ToList();
        }

        public Course GetCourseBy(Func<Course, bool> func)
        {
            return _context.Courses.Include("Students").SingleOrDefault(func);
        }

        public void RemoveStudentFromCourse(int courseId, int id)
        {
            var course = GetCourseBy(x => x.CourseId == courseId);
            var studentToRemove = course.Students.Where(x => x.MemberId == id).SingleOrDefault();
            course.Students.Remove(studentToRemove);
            _context.SaveChanges();
        }

        public CourseDisplayViewModel GetCourseSessions(Course course)
        {
            var currentSessions = _sessionRepository.GetSessionsByCourse(course);
            var sessionsForViewModel = new Dictionary<Member, List<Session>>();
            foreach (Session session in currentSessions)
            {
                Member member = _memberRepository.GetMemberBy(x => x.MemberId == session.StudentId);
                if (!sessionsForViewModel.Keys.Contains(member))
                {
                    sessionsForViewModel[member] = new List<Session>();
                }
                sessionsForViewModel[member].Add(session);
            }
            return new CourseDisplayViewModel
            {
                Course = course,
                Sessions = sessionsForViewModel
            };
        }
    }
}